// pages/odd-group/index.js
//获取应用实例
const app = getApp();
var url = getApp().globalData.ApiUrl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    kanjia_list: [],   // 砍价列表
    page: 10,    // 每页默认显示个数
    curpage: 1,   // 页码
    hots: 0,      // 是否为热门砍价列表 是传1
    hasMoreData: true,
    goods_img: '',
    propertyChildNames: '',
    num: 1,
  },
  rightTap: function () {
    wx.navigateTo({
      url: '/pages/odd/index',
    })
  },
  skipTap: function (e) {
    var dataset = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + dataset.goods_id,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getMusicInfo()
  },
  toBargain: function (e){
    var that = this;
    var dataset = e.currentTarget.dataset;
    var goods_img = e.currentTarget.dataset.goods_img;
    var mobile = wx.getStorageSync("mobile");
    if (!mobile) {
      wx.navigateTo({
        url: '/pages/phone/index',
      })
    };
    that.setData({
      showView: true,
      goods_img: goods_img
    });
    that.getDetails(dataset);
  },
  /**
   * 切换规格选中状态
   * @author chelfinn
   * @date 2018-09-18
   */
  clickTap: function (e) {
    var that = this;
    var specALLArr = that.data.specALLArr;
    var childs = that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData;
    // 取消该分类下的子栏目所有的选中状态
    for (var i = 0; i < childs.length; i++) {
      that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[i].active = false;
    }
    // 设置当前选中状态
    that.data.specALLArr[e.currentTarget.dataset.propertyindex].twoData[e.currentTarget.dataset.propertychildindex].active = true;
    that.setData({
      specALLArr: specALLArr
    });
    // 循环数组 获取点中状态时的规格
    for (var id in specALLArr) {
      for (var i in specALLArr[id].twoData) {
        if (specALLArr[id].twoData[i].active == true) {
          ids.push(specALLArr[id].twoData[i].id);  // 获取的商品选中时的id
          valus.push(specALLArr[id].twoData[i].name);   // 获取商品点中时的规格
        }
      };
    };
    var spec_id = ids.sort().join("|");   // 升序
    var spec_value = valus.toString().replace(/,/g, " ");  // 选中的规格
    var spec_list = that.data.detailData.spec_list;
    if (spec_value) {
      this.setData({
        propertyChildNames: spec_value,
      })
    };
    if (spec_id in spec_list) {
      that.setData({
        buyGoods_id: spec_list[spec_id], //获取购买的商品id
      });
    };
    // 获取商品详情
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: that.data.buyGoods_id
      },
      success: (res) => {
        if (res.data.code == 200) {
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          for (var i in specObj) {
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];
            for (var j in res.data.datas.goods_info.spec_value[i]) {
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          if (datas.goods_info.kanjia_promotion == 1) {
            that.setData({
              detailData: datas,  //商品详情
              buyGoods_id: datas.goods_info.goods_id, //购买的商品id
              goods_price: datas.goods_info.kanjia_price, //商品价格
              goods_storage: datas.goods_info.goods_storage, //商品库存
              showView: true,
            })
          } else {
            that.setData({
              detailData: datas,  //商品详情
              buyGoods_id: datas.goods_info.goods_id, //购买的商品价格
              goods_price: datas.goods_info.goods_price, //商品价格
              goods_storage: datas.goods_info.goods_storage, //商品库存
              showView: true
            });
          };
          if (that.data.goods_storage == 0) {
            this.setData({
              showSure: false
            });
          } else {
            that.setData({
              showSure: true
            })
          };
        };
        if (res.data.code == 400) {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  /**
   * 立即购买
   */
  groupBuyNow: function (e) {
    var that = this;
    /**
     * log_id 参团id,自己发起的团,支付成功后返回的id，有则传，无则不传，不能穿空    pintuan_id 不为空时，为拼主的拼团号
     * pintuan    拼团的话设置为1，默认为空
     * status 1普通购买，2拼团，3秒杀
     */
    var ifcart = '';
    var log_id = '';
    var goods_id = e.currentTarget.dataset.goods_id;
    //item 店铺名，商品名，商品图片，选中规格，商品单价，数量
    var item = {};
    item.store_name = that.data.goods_details.store_info.store_name;
    item.store_id = that.data.goods_details.store_info.store_id;
    item.goods_name = that.data.goods_details.goods_info.goods_name;
    item.goods_price = that.data.goods_price;
    item.spec_name = that.data.propertyChildNames;
    item.goods_num = that.data.num;
    item = JSON.stringify(item);
    var totalPrice = that.data.goods_price;
    var cart_id = goods_id + '|1';

    var item1 = JSON.parse(item);
    var storega = that.data.goods_storage;
    var arr = item1.spec_name.split(" ");
    if (this.data.specALLArr.length == 0) {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他上商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      wx.navigateTo({
        url: '/pages/submit-order/index?status=1&cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_kanjia=1',
      });
    } else {
      if (storega == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他上商品',
          showCancel: false,
        })
        this.setData({
          showView: false
        })
        return;
      }
      if (arr.length != this.data.specALLArr.length) {
        wx.showModal({
          title: '提示',
          content: '请先选择商品规格尺寸哟~',
          showCancel: false,
        })
        return;
      }
      wx.navigateTo({
        url: '/pages/submit-order/index?status=1&cart_id=' + cart_id + '&ifcart=' + ifcart + '&is_kanjia=1', 
      });
    }
  },
  /**
   * 关闭弹窗
   */
  errorTap: function () {
    this.setData({
      showView: false,
      propertyChildNames: '',
    });
  },
  /**
	* 获取商品详情
	*/
  getDetails: function (dataset) {
    var that = this;
    //获取商品详情
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: dataset.goods_id
      },
      success: (res) => {
        if (res.data.code == 200) {
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var imgURL = res.data.datas.goods_image.split(',');
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          var specALLArr = []; // 商品规格和商品
          var goods_spec = [];
          var spec_id = [];
          for (var spec_d in res.data.datas.goods_info.goods_spec) {
            goods_spec.push(res.data.datas.goods_info.goods_spec[spec_d]);  // 商品规格
            spec_id.push(spec_d);
            var spec = goods_spec.toString().replace(/,/g, " ");
          };
          for (var i in specObj) {
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];
            for (var j in res.data.datas.goods_info.spec_value[i]) {
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp2.active = (j in res.data.datas.goods_info.goods_spec) ? true : false;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));
            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          if (spec) {
            this.setData({
              propertyChildNames: spec,
            })
          };
          that.setData({
            imgUrl: imgURL,
            sum: imgURL.length,
            goods_details: res.data.datas,
            specALLArr: specALLArr,
            detailData: datas,  //商品详情
            buyGoods_id: dataset.goods_id, //购买的商品价格
            goods_price: datas.goods_info.kanjia_price, //砍价价格
            goods_storage: datas.goods_info.goods_storage, //商品库存
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 1500
        })
      }
    });
  },
  // 获取砍价商品列表
  getMusicInfo: function() {
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: url + '/mobile/index.php?act=api&op=get_kanjia_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      success: (res) => {
        if (res.data.code == 200) {
          var size = this.data.page;   // 数据长度
          var curpage = this.data.curpage;   // 数据页码
          wx.hideLoading();
          var arr = [];
          for (var i in res.data.datas) {
            arr.push(res.data.datas[i]);
          }
          if (arr.length < size) {    // 如果数据长度除以10小于
            this.setData({
              kanjia_list: arr,
              page: arr.length,
              curpage: curpage
            })
          } else {
            this.setData({
              kanjia_list: arr.concat(arr),
              curpage: this.data.curpage++,
              page: arr.length
            })
          }
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多了',
          icon: 'none',
          duration: 1500,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.curpage = 1;
    this.getMusicInfo('正在刷新数据');
    // setTimeout(function(){
    wx.stopPullDownRefresh()
    // },3000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var size = this.data.page;
    var list = this.data.kanjia_list;
    if (size < list.length) {
      this.data.curpage = this.data.curpage++;
      this.getMusicInfo("加载更多数据")
    } else {
      wx.showToast({
        title: '没有更多数据',
        icon: "none"
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})